//
//  PictureView.m
//  UI09_homework
//
//  Created by 洛洛大人 on 16/6/17.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "PictureView.h"
#import "SecondScrollView.h"

@interface PictureView()<UIScrollViewAccessibilityDelegate>

@property (nonatomic, retain)SecondScrollView *scrollView;

@property (nonatomic, retain)UIPageControl *pageControl;


@end


@implementation PictureView

-(void)dealloc {
    [_imageArray release];
    [_scrollView release];
    [_pageControl release];
    [super dealloc];

}

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    self.imageArray = [NSArray array];
        
    [self creatSubView];
    }
    return self;
    
 }

-(void)creatSubView {
    
    self.scrollView = [[SecondScrollView alloc]initWithFrame:self.frame];
    self.scrollView.backgroundColor = [UIColor grayColor];
    
    [self addSubview:self.scrollView];
    [self.scrollView release];
    
    
    
    self.scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.bounds), 0);

    self.scrollView.delegate = self;
    
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds) / 5 * 3, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) / 5 * 2)];
    
    
    [self addSubview:self.pageControl];
    
    self.pageControl.numberOfPages = self.imageArray.count;
    [_pageControl release];
    
    [self.pageControl addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
    
}

-(void)pageAction:(UIPageControl *)pageControl {
    
    
    [self.scrollView setContentOffset:CGPointMake((pageControl.currentPage + 1) * CGRectGetWidth(self.bounds), 0) animated:YES];
    
    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.x >= (self.imageArray.count - 1) * CGRectGetWidth(self.bounds)) {
        
        scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.bounds), 0);
        
    } else if (scrollView.contentOffset.x <= 0) {
        
        scrollView.contentOffset = CGPointMake((self.imageArray.count - 2) * CGRectGetWidth(self.bounds), 0);
        
    }
   
    self.pageControl.currentPage = (scrollView.contentOffset.x - CGRectGetWidth(self.bounds)) / CGRectGetWidth(self.bounds);
    
}


-(void)setImageArray:(NSArray<UIImage *> *)imageArray {
    
    if (_imageArray != imageArray) {
        [_imageArray release];
        _imageArray = [imageArray retain];
    }
    
    [self.scrollView addPicture:_imageArray];
    self.pageControl.numberOfPages = _imageArray.count - 2;
    
    
}
















@end
